<template>
  <div class="shopping-list-container">
    <!-- 顶部导航栏 -->
    <header class="main-header">
      <div class="header-content">
        <div class="logo">西湖分信用商城</div>
        <nav class="main-nav">
          <ul>
            <!-- <li><a href="#" @click="handleHomeNavigation">首页</a></li> -->
            <!-- <li><a href="#" @click="handleShopNavigation">商店</a></li> -->
            <li class="dropdown-parent" @mouseover="showCategoryDropdown = true" @mouseleave="showCategoryDropdown = false">
              <a href="#">分类</a>
              <ul class="dropdown-menu" v-if="showCategoryDropdown">
                <li @click="filterByCategory('所有分类')">所有分类</li>
                <li v-for="cat in categories" :key="cat.name" @click="filterByCategory(cat.name)">
                  {{ cat.name }}
                </li>
              </ul>
            </li>
            <li><a href="#" @click="handleBlogNavigation">博客</a></li>
            <li><a href="#" @click="handleContactNavigation">联系我们</a></li>
          </ul>
        </nav>
        <div class="header-right">
          <div class="search-bar">
            <input type="text" placeholder="搜索 (例如：手机，笔记本)" v-model="searchQuery" @keyup.enter="handleSearch" />
            <el-icon class="search-icon" @click="handleSearch"><Search /></el-icon>
          </div>
          <div class="user-cart-icons">
            <el-icon @click="goToUserProfile"><User /></el-icon>
            <el-icon @click="goToCart"><ShoppingCart /></el-icon>
          </div>
        </div>
      </div>
    </header>

    <!-- 主体内容 -->
    <main class="main-content">
      <!-- Hero Section -->
      <section class="hero-section">
        <div class="hero-text">
          <h1>构建电商巨头</h1>
          <h2>西湖分信用商城</h2>
          <p>无缝整合企业指标，无需基于性能的流程</p>
          <div class="hero-buttons">
            <button class="browse-store-button" @click="browseStore">浏览商店 →</button>
          </div>
        </div>
        <div class="hero-image">
          <img src="https://via.placeholder.com/400x300?text=Product+Image" alt="Product" />
          <div class="discount-badge">
            <span class="discount-percent">35%off</span>
            <span class="discount-category">现代家具</span>
          </div>
          <div class="time-indicator">
            <span>19 03</span>
          </div>
        </div>
      </section>

      <!-- 分类图标区域 -->
      <section class="categories-section">
        <div class="category-item" @click="filterByCategory('电子产品')">
          <el-icon><Brush /></el-icon>
          <span>电子产品</span>
        </div>
        <div class="category-item" @click="filterByCategory('小工具')">
          <el-icon><Headset /></el-icon>
          <span>小工具</span>
        </div>
        <div class="category-item" @click="filterByCategory('家具')">
          <el-icon><HomeFilled /></el-icon>
          <span>家具</span>
        </div>
        <div class="category-item" @click="filterByCategory('椅子')">
          <el-icon><Goods /></el-icon>
          <span>椅子</span>
        </div>
        <div class="category-item" @click="filterByCategory('书籍')">
          <el-icon><Reading /></el-icon>
          <span>书籍</span>
        </div>
        <div class="category-item" @click="filterByCategory('汽车')">
          <el-icon><Van /></el-icon>
          <span>汽车</span>
        </div>
        <div class="category-item" @click="filterByCategory('自行车')">
          <el-icon><Bicycle /></el-icon>
          <span>自行车</span>
        </div>
        <div class="category-item" @click="filterByCategory('健身')">
          <el-icon><Goods /></el-icon>
          <span>健身</span>
        </div>
      </section>

      <!-- 商品列表区域 -->
      <section class="product-list-section">
        <div class="product-card" v-for="product in filteredProducts" :key="product.id" @click="goToProductDetail(product.id)">
          <img :src="product.image" alt="Product Image" />
          <h3>{{ product.name }}</h3>
          <p class="original-price" v-if="product.originalPrice !== product.discountedPrice">¥{{ product.originalPrice }}</p>
          <p class="discounted-price">¥{{ product.discountedPrice }}</p>
          <span class="discount-tag" v-if="product.discountRate > 0">{{ (product.discountRate * 100).toFixed(0) }}% 折扣</span>
        </div>
        <div v-if="filteredProducts.length === 0" class="no-products-found">
          <p>没有找到相关商品。</p>
        </div>
      </section>
    </main>

    <!-- Product Detail Dialog -->
    <el-dialog
      v-model="productDetailDialogVisible"
      title="商品详情"
      width="50%"
      v-if="selectedProduct"
    >
      <div class="product-detail-dialog-content">
        <div class="dialog-image">
          <img :src="selectedProduct.image" :alt="selectedProduct.name" />
        </div>
        <div class="dialog-info">
          <h3>{{ selectedProduct.name }}</h3>
          <p>类别: {{ selectedProduct.category }}</p>
          <p class="original-price" v-if="selectedProduct.originalPrice !== selectedProduct.discountedPrice">原价: ¥{{ selectedProduct.originalPrice }}</p>
          <p class="discounted-price">当前价格: ¥{{ selectedProduct.discountedPrice }}</p>
          <p class="description">描述: 这是一个{{ selectedProduct.name }}的详细描述。这里可以添加更多关于商品的具体信息，例如材质、功能、尺寸等。</p>
          <div class="dialog-actions">
            <el-input-number v-model="productQuantity" :min="1" :max="10" /> <!-- 假设最大购买数量为10 -->
            <el-button type="primary" @click="handleAddToCart(selectedProduct)">加入购物车</el-button>
            <el-button type="success" @click="handleBuyNow(selectedProduct)">立即购买</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElDialog } from 'element-plus' // Import ElMessage and ElDialog
import {
  Search,
  User,
  ShoppingCart,
  Brush,
  Headset,
  HomeFilled,
  Goods,
  Reading,
  Van,
  Bicycle
} from '@element-plus/icons-vue'

const router = useRouter()

const searchQuery = ref('')
const showCategoryDropdown = ref(false); // 控制分类下拉框显示
const currentCategory = ref('所有分类'); // 当前选中的分类

const productDetailDialogVisible = ref(false); // 控制商品详情弹窗显示
const selectedProduct = ref(null); // 选中的商品
const productQuantity = ref(1); // 弹窗中选择的商品数量

// 商品分类定义
const categories = ref([
  { name: '电子产品', icon: 'Brush' },
  { name: '小工具', icon: 'Headset' },
  { name: '家具', icon: 'HomeFilled' },
  { name: '椅子', icon: 'Goods' },
  { name: '书籍', icon: 'Reading' },
  { name: '汽车', icon: 'Van' },
  { name: '自行车', icon: 'Bicycle' },
  { name: '健身', icon: 'Goods' }, // 假设Goods作为健身图标的替代
]);

const products = ref([
  {
    id: 1,
    name: '智能手表',
    image: 'https://via.placeholder.com/200x200?text=Smart+Watch',
    originalPrice: 198,
    category: '电子产品', // 添加分类信息
    stock: 50, // 假设库存
    discountedPrice: 124 // 假设这是计算后的价格
  },
  {
    id: 2,
    name: '木质笔筒',
    image: 'https://via.placeholder.com/200x200?text=Wood+Pen+Holder',
    originalPrice: 198,
    category: '家具', // 添加分类信息
    stock: 30,
    discountedPrice: 124
  },
  {
    id: 3,
    name: '环保袋',
    image: 'https://via.placeholder.com/200x200?text=Eco+Bag',
    originalPrice: 198,
    category: '电子产品', // 添加分类信息
    stock: 100,
    discountedPrice: 124
  },
  {
    id: 4,
    name: '桌面植物',
    image: 'https://via.placeholder.com/200x200?text=Table+Plant',
    originalPrice: 198,
    category: '家具', // 添加分类信息
    stock: 20,
    discountedPrice: 124
  },
  {
    id: 5,
    name: '经典小说',
    image: 'https://via.placeholder.com/200x200?text=Classic+Novel',
    originalPrice: 50,
    category: '书籍', // 添加分类信息
    stock: 80,
    discountedPrice: 45
  },
  {
    id: 6,
    name: '运动哑铃',
    image: 'https://via.placeholder.com/200x200?text=Dumbbell',
    originalPrice: 150,
    category: '健身', // 添加分类信息
    stock: 40,
    discountedPrice: 120
  }
]);

// 假设用户信用分，从 Home.vue 或全局状态获取
const userCreditScore = ref(655); // 示例信用分

// 根据信用分计算折扣，这里只是一个示例逻辑
const calculateDiscountedPrice = (originalPrice, creditScore) => {
  let discountRate = 0;
  if (creditScore >= 700) {
    discountRate = 0.3; // 30% off for excellent credit
  } else if (creditScore >= 600) {
    discountRate = 0.2; // 20% off for good credit
  } else if (creditScore >= 500) {
    discountRate = 0.1; // 10% off for average credit
  }
  const discountedPrice = (originalPrice * (1 - discountRate)).toFixed(2);
  return { discountedPrice, discountRate };
};

// 在组件加载时计算所有商品的折扣价格和折扣率
products.value = products.value.map(product => {
  const { discountedPrice, discountRate } = calculateDiscountedPrice(product.originalPrice, userCreditScore.value);
  return { ...product, discountedPrice, discountRate };
});

const filteredProducts = computed(() => {
  let filtered = products.value;

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(product =>
      product.name.toLowerCase().includes(query)
    );
  }

  if (currentCategory.value !== '所有分类') {
    filtered = filtered.filter(product => product.category === currentCategory.value);
  }

  return filtered;
});

const handleSearch = () => {
  console.log('Searching for:', searchQuery.value);
  // 搜索逻辑现在由 computed 属性 filteredProducts 处理
};

const handleHomeNavigation = () => {
  router.push('/home');
};

// handleShopNavigation 已移除，因为"商店"按钮已删除

const filterByCategory = (categoryName) => {
  currentCategory.value = categoryName;
  showCategoryDropdown.value = false; // 点击分类后关闭下拉框
};

const handleCategoryNavigation = () => {
  // 导航栏的"分类"只用于显示下拉框，不直接进行导航
};

const handleBlogNavigation = () => {
  console.log('Navigate to Blog page');
  // router.push('/blog'); // 如果有博客页面路由
};

const handleContactNavigation = () => {
  console.log('Navigate to Contact Us page');
  // router.push('/contact'); // 如果有联系我们页面路由
};

const goToUserProfile = () => {
  router.push('/user/profile');
};

const goToCart = () => {
  router.push('/credit/credit-business/business-shopping/cart');
};

const browseStore = () => {
  router.push('/credit/credit-business/business-shopping/shopping-list');
};

const goToProductDetail = (productId) => {
  selectedProduct.value = products.value.find(p => p.id === productId);
  if (selectedProduct.value) {
    productDetailDialogVisible.value = true;
    productQuantity.value = 1; // 打开弹窗时重置数量
  }
};

const handleAddToCart = (product) => {
  console.log(`加入购物车: ${product.name}, 数量: ${productQuantity.value}`);
  ElMessage.success(`${product.name} x ${productQuantity.value} 已加入购物车!`);
  productDetailDialogVisible.value = false; // 关闭弹窗
  // 这里可以添加实际的添加到购物车API调用逻辑
};

const handleBuyNow = (product) => {
  console.log(`立即购买: ${product.name}, 数量: ${productQuantity.value}`);
  ElMessage.success(`您已购买 ${product.name} x ${productQuantity.value}！`);
  productDetailDialogVisible.value = false; // 关闭弹窗
  router.push('/credit/credit-business/business-shopping/cart'); // 假设购买后跳转到购物车或结算页
  // 这里可以添加实际的立即购买/结算API调用逻辑
};

</script>

<style scoped>
.shopping-list-container {
  font-family: Arial, sans-serif;
  background-color: #f8f8f8;
  color: #333;
}

/* Header Styles */
.main-header {
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 15px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.main-nav ul {
  list-style: none;
  display: flex;
  margin: 0;
  padding: 0;
}

.main-nav li a {
  text-decoration: none;
  color: #555;
  padding: 0 15px;
  font-weight: 500;
}

.main-nav li a:hover {
  color: #007bff;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-bar {
  position: relative;
  margin-right: 20px;
}

.search-bar input {
  border: 1px solid #ccc;
  border-radius: 20px;
  padding: 8px 15px 8px 35px;
  width: 250px;
  outline: none;
}

.search-bar .search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  cursor: pointer;
}

.user-cart-icons .el-icon {
  font-size: 20px;
  margin-left: 15px;
  cursor: pointer;
  color: #555;
}

/* Main Content Styles */
.main-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* Hero Section */
.hero-section {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 40px;
}

.hero-text {
  flex: 1;
  padding: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.hero-text h1 {
  font-size: 48px;
  color: #333;
  margin-bottom: 10px;
}

.hero-text h2 {
  font-size: 36px;
  color: #007bff;
  margin-bottom: 20px;
}

.hero-text p {
  font-size: 16px;
  color: #777;
  line-height: 1.6;
  margin-bottom: 30px;
}

.browse-store-button {
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 12px 25px;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.browse-store-button:hover {
  background-color: #0056b3;
}

.hero-image {
  flex: 1;
  position: relative;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hero-image img {
  max-width: 100%;
  height: auto;
  display: block;
}

.discount-badge {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: #007bff;
  color: #fff;
  padding: 10px 15px;
  border-radius: 5px;
  text-align: center;
}

.discount-percent {
  font-size: 24px;
  font-weight: bold;
  display: block;
}

.discount-category {
  font-size: 14px;
}

.time-indicator {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);;
  color: #fff;
  padding: 8px 15px;
  border-radius: 5px;
  font-size: 18px;
}

/* Categories Section */
.categories-section {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 30px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 40px;
}

.category-item {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.category-item .el-icon {
  font-size: 36px;
  color: #007bff;
  margin-bottom: 10px;
}

.category-item span {
  font-size: 14px;
  font-weight: 500;
  color: #555;
}

/* Product List Section */
.product-list-section {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  text-align: center;
  transition: transform 0.3s ease;
  position: relative; /* For discount tag positioning */
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-card img {
  max-width: 100%;
  height: 180px; /* Consistent height for product images */
  object-fit: contain;
  margin-bottom: 15px;
}

.product-card h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.product-card .original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-bottom: 5px;
}

.product-card .discounted-price {
  font-size: 20px;
  font-weight: bold;
  color: #dc3545; /* Red color for discounted price */
}

.discount-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: #28a745; /* Green for discount */
  color: #fff;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px;
  font-weight: bold;
}

.no-products-found {
  grid-column: 1 / -1; /* Span across all columns */
  text-align: center;
  padding: 50px;
  color: #606266;
  font-size: 16px;
}

/* Dropdown Styles */
.dropdown-parent {
  position: relative;
  cursor: pointer;
}

.dropdown-menu {
  position: absolute;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  list-style: none;
  padding: 10px 0;
  margin-top: 10px;
  min-width: 120px;
  z-index: 1000;
}

.dropdown-menu li {
  padding: 8px 15px;
  cursor: pointer;
  white-space: nowrap;
  /* display: block; 被移除，恢复默认 */
}

.dropdown-menu li:hover {
  background-color: #f5f7fa;
  color: #007bff;
}

/* Product Detail Dialog Styles */
.product-detail-dialog-content {
  display: flex;
  gap: 20px;
}

.dialog-image img {
  width: 200px;
  height: 200px;
  object-fit: contain;
  border: 1px solid #eee;
  border-radius: 4px;
}

.dialog-info {
  flex: 1;
}

.dialog-info h3 {
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
}

.dialog-info p {
  margin-bottom: 5px;
  color: #666;
}

.dialog-info .original-price {
  text-decoration: line-through;
  color: #999;
}

.dialog-info .discounted-price {
  font-size: 22px;
  font-weight: bold;
  color: #dc3545;
  margin-bottom: 15px;
}

.dialog-actions {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}
</style> 